package com.cssy.yd.logic.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.yd.logic.dao.LogicFkReturnDAO;
import com.cssy.yd.logic.dao.LogicFkReturnItemDAO;
import com.cssy.yd.logic.dao.LogicPoReturnDAO;
import com.cssy.yd.logic.entity.LogicPoReturnDO;
import com.cssy.yd.logic.entity.LogicFkReturnDO;
import com.cssy.yd.logic.entity.LogicFkReturnItemDO;
import com.cssy.yd.logic.service.ILogicFkReturnService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.exception.SyCodeException;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicFkReturnService")
public class LogicFkReturnServiceImpl implements ILogicFkReturnService {
	@Resource(name = "logicFkReturnDAO")
	private LogicFkReturnDAO logicFkReturnDAO;

	@Resource(name = "logicFkReturnItemDAO")
	private LogicFkReturnItemDAO logicFkReturnItemDAO;

	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Resource(name = "logicPoReturnDAO")
	private LogicPoReturnDAO logicPoReturnDAO;

	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs = new SearchResult(scs);
		List<LogicFkReturnDO> list = logicFkReturnDAO.find(scs);
		rs.setRecordCount(logicFkReturnDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		Integer i = logicFkReturnDAO.deleteLogicFkReturnDOByPrimaryKey(id);
		return i;
	}

	@Override
	public Integer update(LogicFkReturnDO t, User user) throws SyBaseException {
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		return logicFkReturnDAO.updateLogicFkReturnDO(t);
	}

	@Override
	public LogicFkReturnDO save(LogicFkReturnDO t, User user) throws SyBaseException {
		t.setDcruser(user.getName());
		t.setDctime(new Date());
		t.setId(IDCodeTypeUtil.getId());
		logicFkReturnDAO.insertLogicFkReturnDO(t);
		return t;
	}

	@Override
	public LogicFkReturnDO findListById(String id) throws SyBaseException {
		return logicFkReturnDAO.findLogicFkReturnDOByPrimaryKey(id);
	}

	@Override
	public SearchResult findItemListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs = new SearchResult(scs);
		List<LogicFkReturnItemDO> list = logicFkReturnItemDAO.find(scs);
		rs.setRecordCount(logicFkReturnItemDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer deleteItem(String id) throws SyBaseException {
		Integer i = logicFkReturnItemDAO.deleteLogicFkReturnItemDOByPrimaryKey(id);
		return i;
	}

	@Override
	public Integer updateItem(LogicFkReturnItemDO t) throws SyBaseException {
		return logicFkReturnItemDAO.updateLogicFkReturnItemDO(t);
	}

	@Override
	public LogicFkReturnItemDO saveItem(LogicFkReturnItemDO t) throws SyBaseException {
		t.setId(IDCodeTypeUtil.getId());
		logicFkReturnItemDAO.insertLogicFkReturnItemDO(t);
		return t;
	}

	@Override
	public List<LogicFkReturnItemDO> findItemListBytkid(String tkid)
			throws SyBaseException {

		return logicFkReturnItemDAO.finditembytkid(tkid);
	}

	@Override
	public Double findLastedDOByExample(SearchConditions scs)
			throws SyBaseException {
		return logicFkReturnDAO.findLastedDOByOricode(scs);
	}

	@Override
	public LogicFkReturnItemDO findItemListById(String id) throws SyBaseException {
		return logicFkReturnItemDAO.findLogicFkReturnItemDOByPrimaryKey(id);
	}

	@Override
	public void fkReturnSave(HttpServletRequest request, LogicFkReturnDO curAP)
			throws SyBaseException, SyCodeException {
		try {//新增草稿
			String tkDate = request.getParameter("tkDate");
			String itemdata = request.getParameter("itemdata");	
 			List<LogicFkReturnItemDO> itemlist = JSONArray.parseArray(itemdata, LogicFkReturnItemDO.class);	
 			// 检查是否已有此采购退货单的退款单草稿
			String oricode = request.getParameter("oriCode");
			SearchConditions scs = new SearchConditions();
			scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus", "0", SearchCondition.OP_EQUAL);
			int tkcount = logicFkReturnDAO.count(scs);
			if(tkcount > 0){
				throw new SyBaseException("已有此采购退货的退款单草稿，请先处理已有的单据");
			}		
			 
				String id = IDCodeTypeUtil.getId();
				curAP.setId(id);
				curAP.setTkCode(syCodeService.getCode("FKTK","FKTK",SyCode.DATE_YYMM,5));
				String tkcode = curAP.getTkCode();
				curAP.setBillStatus(0);
				curAP.setRefundStatus(0);
				curAP.setDcruser(SessionUtil.getUser(request).getName());
				curAP.setDctime(new Date());
				if (tkDate != null && !"".equals(tkDate)) {
					curAP.setTkDate(DateUtils.stringToDate(tkDate));
				}	
				logicFkReturnDAO.insertLogicFkReturnDO(curAP);
				for (int i = 0; i < itemlist.size(); i++) {
					itemlist.get(i).setId(IDCodeTypeUtil.getId());
					itemlist.get(i).setTkid(id);
					itemlist.get(i).setTkcode(tkcode);
					logicFkReturnItemDAO.insertLogicFkReturnItemDO(itemlist.get(i));
				}
 			
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}
	
	@Override
	public void fkReturnCommit(HttpServletRequest request, LogicFkReturnDO curAP)
			throws SyBaseException, SyCodeException {
		try {
			String tkDate = request.getParameter("tkDate");
			String itemdata = request.getParameter("itemdata");	
			String itemdelete = request.getParameter("itemdelete");
			String returnpocode = request.getParameter("oriCode");
 			List<LogicFkReturnItemDO> itemlist = JSONArray.parseArray(itemdata, LogicFkReturnItemDO.class);	
 			List<LogicPoReturnDO> poreturnlist = new ArrayList<LogicPoReturnDO>();
 			LogicPoReturnDO pd = null;
 			Double presthk = Double.parseDouble("0");  //本次实退采购款
 			Double prewthk = Double.parseDouble("0"); //本次剩余未退采购款
 			if (itemdelete != null && !"".equals(itemdelete)) {
				List<LogicFkReturnItemDO> frilist = JSONArray.parseArray(itemdelete, LogicFkReturnItemDO.class);
				for (LogicFkReturnItemDO frido : frilist) {
					if (frido.getId() != null&& !"".equals(frido.getId())) {
						logicFkReturnItemDAO.deleteLogicFkReturnItemDOByPrimaryKey(frido.getId());
					}
				}
			}
 			//提交付款退款单
 			if(itemlist != null && itemlist.size() > 0){
				for (LogicFkReturnItemDO skitem : itemlist) {
					skitem.setYthk((skitem.getYthk()==null ? 0 : skitem.getYthk()) + (skitem.getSthk()==null?0:skitem.getSthk()));
					skitem.setWthk((skitem.getWthk()==null ? 0 : skitem.getWthk()) - (skitem.getSthk()==null ? 0 : skitem.getSthk()));
					skitem.setSthk(skitem.getSthk()==null ? 0: skitem.getSthk());
					curAP.setYthk((curAP.getYthk()==null ? 0: curAP.getYthk()) + skitem.getSthk());
					presthk += skitem.getSthk();
					prewthk += skitem.getWthk();
				}
			}
			curAP.setBillStatus(2);
			SearchConditions scs = new SearchConditions();
			scs.addCondition("returnpocode", returnpocode, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus","3", SearchCondition.OP_EQUAL);
			poreturnlist = logicPoReturnDAO.find(scs);
			if(poreturnlist!=null&&poreturnlist.size()>0){ //取得对应的采购退货单
				pd = poreturnlist.get(0);
			}
 			SearchConditions scs1 = new SearchConditions();
			scs1.addCondition("oricode", returnpocode, SearchCondition.OP_EQUAL);
			scs1.addCondition("billstatus","2", SearchCondition.OP_EQUAL);
 			Double hisythk = logicFkReturnDAO.findLastedDOByOricode(scs1);//最近一次退款后的已退金额	
 			Double hiswthk = new Double("0.0");
 			
 			if(hisythk == null||hisythk==0){
 				hisythk = Double.parseDouble("0.0");
 			}
 			hiswthk = new BigDecimal(curAP.getAmount().toString()).subtract(new BigDecimal(hisythk.toString())).doubleValue(); //最近一次收款后的未收金额
 			if(presthk.doubleValue() < hiswthk.doubleValue()) {
 				curAP.setRefundStatus(1);
 				if(pd.getId()!=null){
 					pd.setPaymentstatus(1);  //根据收款情况改变销售出库单中的付款状态
 				}
 			} else if(presthk.doubleValue() == hiswthk.doubleValue()){
 				curAP.setRefundStatus(2);
 				if(pd.getId()!=null){
 					pd.setPaymentstatus(2);
 				}
 			} else if(presthk.doubleValue() > hiswthk.doubleValue()) {
 				throw new SyBaseException("您本次付款大于付款单历史未付款！");
 			}
 			
 			int j = logicPoReturnDAO.updateLogicPoReturnDO(pd);
			if(j < 0){
				throw new SyBaseException("提交失败");
			}
			if (tkDate != null && !"".equals(tkDate)) {
				curAP.setTkDate(DateUtils.stringToDate(tkDate));
			}	
			curAP.setBillStatus(2);
			curAP.setDuuser(SessionUtil.getUser(request).getName());
			curAP.setDutime(new Date());
			logicFkReturnDAO.updateLogicFkReturnDO(curAP);
			for (int i = 0; i < itemlist.size(); i++) {
				logicFkReturnItemDAO.updateLogicFkReturnItemDO(itemlist.get(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		// TODO Auto-generated method stub
		return null;
	}

}
